whenReady(() => {
  let goRegister = document.querySelector('.goRegister');
  let goLogin = document.querySelector('.goLogin');
  let loginForm = document.querySelector('#loginForm');
  let registerForm = document.querySelector('#registerForm');

  goRegister.addEventListener('click', function () {
    registerForm.style.display = 'block';
    loginForm.style.display = 'none';
  });
  goLogin.addEventListener('click', function () {
    registerForm.style.display = 'none';
    loginForm.style.display = 'block';
  });
  loginForm.addEventListener('submit', function (e) {
    e.preventDefault();
    let fd = new FormData(loginForm);
    // fd.forEach(function (v, k) {});
    let xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://ajax.frontend.itheima.net/api/login');
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
    xhr.send(fdToStr(fd));
    xhr.onreadystatechange = function (res) {
      if (xhr.readyState === 4) {
        let data = JSON.parse(xhr.response);
        if (data.status !== 0) return layer.msg(data.message);
        layer.msg(data.message);
        localStorage.setItem('token', data.token);
        location.href = '/index.html';
      }
    };
  });
  registerForm.addEventListener('submit', function (e) {
    e.preventDefault();
    let fd = new FormData(registerForm);
    let xhr = new XMLHttpRequest();
    xhr.open('POST', 'http://ajax.frontend.itheima.net/api/reguser');
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
    xhr.send(fdToStr(fd));
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4) {
        let data = JSON.parse(xhr.responseText);
        if (data.status !== 0) return layer.msg(data.message);
        layer.msg(data.message);
        goLogin.click();
        registerForm.reset();
      }
    };
  });
});
